package com.metro.demo.common.controller;

import com.metro.core.vo.CommonResult;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;
import com.metro.demo.common.beans.constant.CommonConstant;
import com.metro.demo.sys.beans.vo.SysUser;
import com.metro.demo.sys.service.inf.ISysUserService;
import com.metro.demo.web.controller.BaseController;
import com.metro.demo.web.filter.security.vo.BaseUsernamePasswordToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 *  用户登录控制器
 * @author 
 * */
@Controller()
@RequestMapping(value = "/login")
public class LoginController extends BaseController {
	//用户
	@Autowired
	private ISysUserService sysUserService;
	/**
	 * 日志
	 */
	private static final Logger log = LoggerFactory.getLogger(BaseController.class);

	@RequestMapping(value = "/input", method = RequestMethod.GET)
	public String input(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		return "/portal/login";
	}
	@RequestMapping(value = "/checkUser",method=RequestMethod.POST)
	public @ResponseBody
    CommonResult<Object> checkUser(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                   SysUser checkUserInfo, String code) throws Exception {
		CommonResult<Object> cr = new CommonResult<Object>();
		if (StringUtils.isBlank(checkUserInfo.getAccount())
				|| StringUtils.isBlank(checkUserInfo.getPassword())
				) {
			cr.setResult(ResultCode.USER_INVALID_USERNAME_OR_PASS);
			return cr;
		}
		
		Subject currentUser = SecurityUtils.getSubject();  
		
		Session session = currentUser.getSession();
		String code_old = String.valueOf(session.getAttribute(CommonConstant.SESSION_SECURITY_CODE));

		//TODO XK 把校验码去掉上线在放开
		/*if(!code_old.equalsIgnoreCase(code)){
			ResultCode res = ResultCode.CODE_NOT_SAME;
			cr.setResult(res);
			return cr;
		}*/
		
		if (currentUser.isAuthenticated()) {
			currentUser.logout();
		}
		ResultCode res = dologin(currentUser, checkUserInfo);
		if (res == ResultCode.SUCCESS) {
			cr.setResult(res);
			SysUser user = new SysUser();
            user.setLastLoginTime(new Date());
			user.setLastLoginIp(request.getRemoteAddr());
			IResult codeMsg = sysUserService.saveUserLoginInfo(user);
			cr.setResult(codeMsg);
		} else {
			cr.setResult(res);
		}
		return cr;
	}
	
	/**
	 * 登录系统
	 * @param currentUser
	 * @param checkUser
	 * @return
	 */
	private ResultCode dologin(Subject currentUser, SysUser checkUser) {
		ResultCode res = ResultCode.SUCCESS;
		BaseUsernamePasswordToken token = new BaseUsernamePasswordToken(checkUser.getAccount(), checkUser.getPassword());
		try {
			currentUser.login(token);
		} catch (LockedAccountException lae) {
			res = ResultCode.USER_ACCOUNT_IS_LOCKED;
		} catch (UnknownAccountException uae) {
			res = ResultCode.USER_INVALID_USERNAME_OR_PASS;
		} catch (IncorrectCredentialsException ice) {
			res = ResultCode.USER_INVALID_USERNAME_OR_PASS;
		} catch (Exception e) {
		    log.error("登录失败",e);
			res = ResultCode.ERROR;
		}
		return res;
	}
	
	/**
	 * 退出系统
	 * @author xk
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public @ResponseBody
    CommonResult<Object> logout(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		CommonResult<Object> cr = new CommonResult<Object>();
        try {
			Subject currentUser = SecurityUtils.getSubject();  
			if (currentUser.isAuthenticated()) {
				currentUser.logout();
			}
			cr.setResult(ResultCode.SUCCESS);
		} catch (Exception e) {
			log.error("退出系统", e);
			cr.setResult(ResultCode.ERROR);
		}
		return cr;
	}
	
	@RequestMapping(value = "/unauthorized", method = RequestMethod.GET)
	public String unauthorized(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		return "/commons/error/403";
	}
	
}
